package com.leetcode.partition1;

import java.util.Arrays;

/**
 * @author `RKC`
 * @date 2021/8/15 10:43
 */
public class LC52N皇后2 {

    public static int totalNQueens(int n) {
        char[][] chessboard = new char[n][n];
        for (char[] chess : chessboard) {
            Arrays.fill(chess, '.');
        }
        return backtracking(n, 0, chessboard);
    }

    public static void main(String[] args) {
        System.out.println(totalNQueens(8));
    }

    private static int backtracking(int n, int row, char[][] chessboard) {
        if (n == row) return 1;
        int count = 0;
        for (int col = 0; col < n; col++) {
            if (isValid(row, col, chessboard, n)) {
                chessboard[row][col] = 'Q';
                count += backtracking(n, row + 1, chessboard);
                chessboard[row][col] = '.';
            }
        }
        return count;
    }

    private static boolean isValid(int row, int col, char[][] chessboard, int n) {
        // 检查列
        for (int i = 0; i < row; i++) { // 这是⼀个剪枝
            if (chessboard[i][col] == 'Q') {
                return false;
            }
        }
        // 检查 45度⻆是否有皇后
        for (int i = row - 1, j = col - 1; i >=0 && j >= 0; i--, j--) {
            if (chessboard[i][j] == 'Q') {
                return false;
            }
        }
        // 检查 135度⻆是否有皇后
        for(int i = row - 1, j = col + 1; i >= 0 && j < n; i--, j++) {
            if (chessboard[i][j] == 'Q') {
                return false;
            }
        }
        return true;
    }
}
